import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { 
  Upload, 
  Download, 
  Save, 
  Check, 
  X,
  FileText,
  AlertCircle,
  TrendingUp
} from 'lucide-react';

interface Student {
  id: string;
  studentId: string;
  name: string;
  regularScore?: number;
  midtermScore?: number;
  finalScore?: number;
  totalScore?: number;
  grade?: string;
  status: 'draft' | 'submitted' | 'approved';
}

interface GradeSubmission {
  id: string;
  courseName: string;
  className: string;
  examType: string;
  submitDate: string;
  status: 'pending' | 'approved' | 'rejected';
  feedback?: string;
}

export function GradeManagement() {
  const [selectedClass, setSelectedClass] = useState('computer21-1');
  const [editingScore, setEditingScore] = useState<{studentId: string, field: string} | null>(null);

  const students: Student[] = [
    {
      id: '1',
      studentId: '2021001001',
      name: '张三',
      regularScore: 85,
      midtermScore: 88,
      finalScore: 92,
      totalScore: 89,
      grade: 'B+',
      status: 'draft'
    },
    {
      id: '2',
      studentId: '2021001002',
      name: '李四',
      regularScore: 90,
      midtermScore: 85,
      finalScore: 88,
      totalScore: 87,
      grade: 'B',
      status: 'draft'
    },
    {
      id: '3',
      studentId: '2021001003',
      name: '王五',
      regularScore: 78,
      midtermScore: 82,
      finalScore: 85,
      totalScore: 82,
      grade: 'B-',
      status: 'draft'
    },
    {
      id: '4',
      studentId: '2021001004',
      name: '赵六',
      regularScore: 95,
      midtermScore: 92,
      finalScore: 96,
      totalScore: 94,
      grade: 'A',
      status: 'draft'
    }
  ];

  const gradeSubmissions: GradeSubmission[] = [
    {
      id: '1',
      courseName: '高等数学A',
      className: '计算机21-1班',
      examType: '期中考试',
      submitDate: '2024-03-15',
      status: 'approved',
      feedback: '成绩录入准确，已通过审核'
    },
    {
      id: '2',
      courseName: '高等数学A',
      className: '计算机21-2班',
      examType: '期末考试',
      submitDate: '2024-03-18',
      status: 'pending'
    },
    {
      id: '3',
      courseName: '线性代数',
      className: '数学21-1班',
      examType: '平时成绩',
      submitDate: '2024-03-10',
      status: 'rejected',
      feedback: '部分学生成绩需要重新核查'
    }
  ];

  const calculateTotalScore = (regular: number = 0, midterm: number = 0, final: number = 0) => {
    return Math.round(regular * 0.3 + midterm * 0.3 + final * 0.4);
  };

  const getGrade = (score: number) => {
    if (score >= 95) return 'A+';
    if (score >= 90) return 'A';
    if (score >= 85) return 'A-';
    if (score >= 82) return 'B+';
    if (score >= 78) return 'B';
    if (score >= 75) return 'B-';
    if (score >= 72) return 'C+';
    if (score >= 68) return 'C';
    if (score >= 65) return 'C-';
    if (score >= 60) return 'D';
    return 'F';
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'approved':
        return <Badge className="bg-green-100 text-green-800">已通过</Badge>;
      case 'pending':
        return <Badge variant="outline">待审核</Badge>;
      case 'rejected':
        return <Badge variant="destructive">已驳回</Badge>;
      case 'draft':
        return <Badge variant="secondary">草稿</Badge>;
      case 'submitted':
        return <Badge variant="outline">已提交</Badge>;
      default:
        return <Badge variant="outline">未知</Badge>;
    }
  };

  const getClassStats = () => {
    const scores = students.map(s => s.totalScore || 0).filter(s => s > 0);
    const average = scores.length > 0 ? scores.reduce((sum, score) => sum + score, 0) / scores.length : 0;
    const passRate = scores.length > 0 ? (scores.filter(score => score >= 60).length / scores.length) * 100 : 0;
    const excellentRate = scores.length > 0 ? (scores.filter(score => score >= 90).length / scores.length) * 100 : 0;
    
    return {
      average: average.toFixed(1),
      passRate: passRate.toFixed(1),
      excellentRate: excellentRate.toFixed(1)
    };
  };

  const stats = getClassStats();

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-medium">成绩管理</h1>
        <div className="flex gap-2">
          <Button variant="outline">
            <Download className="mr-2 h-4 w-4" />
            下载模板
          </Button>
          <Button variant="outline">
            <Upload className="mr-2 h-4 w-4" />
            批量导入
          </Button>
        </div>
      </div>

      <Tabs defaultValue="entry" className="space-y-4">
        <TabsList>
          <TabsTrigger value="entry">成绩录入</TabsTrigger>
          <TabsTrigger value="review">审核状态</TabsTrigger>
          <TabsTrigger value="statistics">成绩分析</TabsTrigger>
        </TabsList>

        <TabsContent value="entry" className="space-y-4">
          {/* Class Selection */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-4 items-center">
                <label className="text-sm font-medium">选择班级:</label>
                <Select value={selectedClass} onValueChange={setSelectedClass}>
                  <SelectTrigger className="w-48">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="computer21-1">计算机21-1班</SelectItem>
                    <SelectItem value="computer21-2">计算机21-2班</SelectItem>
                    <SelectItem value="math21-1">数学21-1班</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Grade Statistics */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">班级平均分</p>
                    <p className="text-2xl font-medium">{stats.average}</p>
                  </div>
                  <TrendingUp className="h-8 w-8 text-blue-500" />
                </div>
              </CardContent>
            </Card>
            
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">及格率</p>
                    <p className="text-2xl font-medium">{stats.passRate}%</p>
                  </div>
                  <Check className="h-8 w-8 text-green-500" />
                </div>
              </CardContent>
            </Card>
            
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">优秀率</p>
                    <p className="text-2xl font-medium">{stats.excellentRate}%</p>
                  </div>
                  <FileText className="h-8 w-8 text-orange-500" />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Grade Entry Table */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                成绩录入 - 计算机21-1班
                <div className="flex gap-2">
                  <Button variant="outline" size="sm">
                    <Save className="mr-2 h-4 w-4" />
                    保存草稿
                  </Button>
                  <Button size="sm">
                    <Upload className="mr-2 h-4 w-4" />
                    提交审核
                  </Button>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>学号</TableHead>
                    <TableHead>姓名</TableHead>
                    <TableHead>平时成绩(30%)</TableHead>
                    <TableHead>期中成绩(30%)</TableHead>
                    <TableHead>期末成绩(40%)</TableHead>
                    <TableHead>总分</TableHead>
                    <TableHead>等级</TableHead>
                    <TableHead>状态</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {students.map((student) => (
                    <TableRow key={student.id}>
                      <TableCell className="font-medium">{student.studentId}</TableCell>
                      <TableCell>{student.name}</TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          min="0"
                          max="100"
                          value={student.regularScore || ''}
                          className="w-20"
                          placeholder="0-100"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          min="0"
                          max="100"
                          value={student.midtermScore || ''}
                          className="w-20"
                          placeholder="0-100"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          min="0"
                          max="100"
                          value={student.finalScore || ''}
                          className="w-20"
                          placeholder="0-100"
                        />
                      </TableCell>
                      <TableCell className="font-medium">
                        <span className={
                          (student.totalScore || 0) >= 90 ? 'text-green-600' :
                          (student.totalScore || 0) >= 80 ? 'text-blue-600' :
                          (student.totalScore || 0) >= 70 ? 'text-orange-600' :
                          (student.totalScore || 0) >= 60 ? 'text-yellow-600' :
                          'text-red-600'
                        }>
                          {student.totalScore || '-'}
                        </span>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{student.grade || '-'}</Badge>
                      </TableCell>
                      <TableCell>{getStatusBadge(student.status)}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              
              <div className="mt-4 p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-blue-800">
                  <AlertCircle className="inline w-4 h-4 mr-1" />
                  总分计算规则：平时成绩30% + 期中成绩30% + 期末成绩40%
                </p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="review" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>成绩审核状态</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>课程名称</TableHead>
                    <TableHead>班级</TableHead>
                    <TableHead>考试类型</TableHead>
                    <TableHead>提交时间</TableHead>
                    <TableHead>审核状态</TableHead>
                    <TableHead>反馈意见</TableHead>
                    <TableHead>操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {gradeSubmissions.map((submission) => (
                    <TableRow key={submission.id}>
                      <TableCell className="font-medium">{submission.courseName}</TableCell>
                      <TableCell>{submission.className}</TableCell>
                      <TableCell>{submission.examType}</TableCell>
                      <TableCell>{submission.submitDate}</TableCell>
                      <TableCell>{getStatusBadge(submission.status)}</TableCell>
                      <TableCell className="text-sm">
                        {submission.feedback || '-'}
                      </TableCell>
                      <TableCell>
                        <div className="flex space-x-2">
                          <Button variant="ghost" size="sm">
                            查看
                          </Button>
                          {submission.status === 'rejected' && (
                            <Button variant="outline" size="sm">
                              重新编辑
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="statistics" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Score Distribution */}
            <Card>
              <CardHeader>
                <CardTitle>成绩分布</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span>90-100分 (A)</span>
                    <span className="font-medium">
                      {students.filter(s => (s.totalScore || 0) >= 90).length}人 
                      ({((students.filter(s => (s.totalScore || 0) >= 90).length / students.length) * 100).toFixed(1)}%)
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-green-600 h-2 rounded-full" 
                      style={{ width: `${(students.filter(s => (s.totalScore || 0) >= 90).length / students.length) * 100}%` }}
                    ></div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>80-89分 (B)</span>
                    <span className="font-medium">
                      {students.filter(s => (s.totalScore || 0) >= 80 && (s.totalScore || 0) < 90).length}人 
                      ({((students.filter(s => (s.totalScore || 0) >= 80 && (s.totalScore || 0) < 90).length / students.length) * 100).toFixed(1)}%)
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-blue-600 h-2 rounded-full" 
                      style={{ width: `${(students.filter(s => (s.totalScore || 0) >= 80 && (s.totalScore || 0) < 90).length / students.length) * 100}%` }}
                    ></div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>70-79分 (C)</span>
                    <span className="font-medium">
                      {students.filter(s => (s.totalScore || 0) >= 70 && (s.totalScore || 0) < 80).length}人 
                      ({((students.filter(s => (s.totalScore || 0) >= 70 && (s.totalScore || 0) < 80).length / students.length) * 100).toFixed(1)}%)
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-orange-600 h-2 rounded-full" 
                      style={{ width: `${(students.filter(s => (s.totalScore || 0) >= 70 && (s.totalScore || 0) < 80).length / students.length) * 100}%` }}
                    ></div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>60-69分 (D)</span>
                    <span className="font-medium">
                      {students.filter(s => (s.totalScore || 0) >= 60 && (s.totalScore || 0) < 70).length}人 
                      ({((students.filter(s => (s.totalScore || 0) >= 60 && (s.totalScore || 0) < 70).length / students.length) * 100).toFixed(1)}%)
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-yellow-600 h-2 rounded-full" 
                      style={{ width: `${(students.filter(s => (s.totalScore || 0) >= 60 && (s.totalScore || 0) < 70).length / students.length) * 100}%` }}
                    ></div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>0-59分 (F)</span>
                    <span className="font-medium">
                      {students.filter(s => (s.totalScore || 0) < 60).length}人 
                      ({((students.filter(s => (s.totalScore || 0) < 60).length / students.length) * 100).toFixed(1)}%)
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-red-600 h-2 rounded-full" 
                      style={{ width: `${(students.filter(s => (s.totalScore || 0) < 60).length / students.length) * 100}%` }}
                    ></div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Performance Comparison */}
            <Card>
              <CardHeader>
                <CardTitle>班级对比</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="p-4 border rounded-lg">
                    <h4 className="font-medium mb-2">计算机21-1班</h4>
                    <div className="space-y-1 text-sm">
                      <div className="flex justify-between">
                        <span>平均分</span>
                        <span className="font-medium">87.5</span>
                      </div>
                      <div className="flex justify-between">
                        <span>及格率</span>
                        <span className="text-green-600">100%</span>
                      </div>
                      <div className="flex justify-between">
                        <span>优秀率</span>
                        <span className="text-blue-600">25%</span>
                      </div>
                    </div>
                  </div>
                  
                  <div className="p-4 border rounded-lg">
                    <h4 className="font-medium mb-2">计算机21-2班</h4>
                    <div className="space-y-1 text-sm">
                      <div className="flex justify-between">
                        <span>平均分</span>
                        <span className="font-medium">84.2</span>
                      </div>
                      <div className="flex justify-between">
                        <span>及格率</span>
                        <span className="text-green-600">97.4%</span>
                      </div>
                      <div className="flex justify-between">
                        <span>优秀率</span>
                        <span className="text-blue-600">18.4%</span>
                      </div>
                    </div>
                  </div>
                  
                  <div className="p-4 border rounded-lg">
                    <h4 className="font-medium mb-2">数学21-1班</h4>
                    <div className="space-y-1 text-sm">
                      <div className="flex justify-between">
                        <span>平均分</span>
                        <span className="font-medium">89.1</span>
                      </div>
                      <div className="flex justify-between">
                        <span>及格率</span>
                        <span className="text-green-600">100%</span>
                      </div>
                      <div className="flex justify-between">
                        <span>优秀率</span>
                        <span className="text-blue-600">33.3%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}